// 用户页面选择用户后下面表格的关于客户映射关系的表格
const TABLE_ID_USER_CONTACT = 'e_grid_contact';// 表格ID
const TABLE_ID_USER = 'e_grid';// 上面的用户表格ID

$(function(){
    init();// 初始化页面
})

function init(){
    buildTableUserContact();// 初始化表格
}

// 配置表格
function buildTableUserContact() {
    $(`#${TABLE_ID_USER_CONTACT}`).edatagrid({
        method: 'GET',
        param: {},
        title: '关联客户',
        url: '',
        saveUrl: 'usercontact/insert',
        updateUrl: 'usercontact/update',
        destroyUrl: 'usercontact/deleteByPk',
        idField: 'iid',
        destroyMsg: {
            norecord: {	// when no record is selected
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {	// when select a row
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        loadFilter: pageFilter,
        pagination: true,
        pageSize: 200,
        pageNumber: 1,
        pageList: [200, 400, 600, 800, 1000],
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        columns: [[
            {field: 'iid', title: '编号', align: 'center', halign: 'center', sortable: true, hidden: true},
            {
                field: 'contact_code',
                width: 300,
                title: '客户',
                align: 'center',
                halign: 'center',
                sortable: true,
                editor: {
                    type: 'combobox', options: {
                        url: 'jcContactcompany/listQuery',
                        method: 'GET',
                        textField: 'ctName',
                        valueField: 'id',
                        limitToList: true,
                        panelHeight: 200,
                        required: true
                    }
                },
                formatter: (v, r, i) => {
                    if (!v) return '';
                    let prefix = 'user_contact';
                    if (sessionStorage.getItem(prefix + `_` + v) == undefined) {
                        let name = JSON.parse($.ajax({
                            url: `jcContactcompany/queryByPk/${v}`,
                            async: false,
                            dataType: 'json',
                            type: 'GET'
                        }).responseText)['ctName'];
                        sessionStorage.setItem(prefix + `_` + v, name);
                    }
                    return sessionStorage.getItem(prefix + `_` + v);
                }
            },
            {
                field: 'user_id',
                width: 100,
                hidden: true,
                title: '用户ID',
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {}},
                sortable: true,
            },
            {
                field: 'type',
                width: 100,
                hidden: true,
                title: '类型',
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {}},
                sortable: true,
            },
        ]],
        onAdd: function (index, row) {
            // 新增行时将上面表格选中的用户的 id 填充到下面表格列 user_id 上
            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'user_id'
            })
            // let selected = $(`#${TABLE_ID_USER}`).edatagrid('getSelected');
            // if (selected != undefined) {
            //     $(editor.target).textbox('setValue', selected.id);
            // }
            $(editor.target).textbox('setValue', getSelectedUserId());

            // 设置 type = 0 ,用户与客户的关系
            let editorType = $(this).edatagrid('getEditor', {
                index: index,
                field: 'type'
            })
            // 1=客户，2=供应商
            $(editorType.target).textbox('setValue', 1);
        },
        onEdit: function (index, row) {
            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'user_id'
            })
            let selected = $(`#${TABLE_ID_USER}`).edatagrid('getSelected');
            if (selected != undefined) {
                $(editor.target).combobox('setValue', selected.id);
            }
        },
        onBeforeSave: function (index) {
            console.log('onBeforeSave');

            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'user_id'
            });
            return !!$(editor.target).textbox('getValue');
        },
        onLoadSuccess: function () {
            $(this).datagrid('enableFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onLoadError: function () {
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('disable');
                }
            })
            return true;
        },
        onSuccess: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $(this).edatagrid('enableEditing');
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onDestroy: function (index, row) {
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $.messager.alert('提示', row.message, 'warning')
            }
            $(this).edatagrid('reload');
        },
        onError: function (index, row) {
            $.messager.show({title: '提示', msg: row.message});
        },
        toolbar: [
            {
                iconCls: 'icon-reload', text: '刷新', handler: function () {
                    $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('reload');
                }
            },
            {
                iconCls: 'icon-add', text: '新增', handler: function () {
                    $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('addRow');
                }
            },
            {
                iconCls: 'icon-edit', text: '修改', handler: function () {
                    let selected = $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('getSelected');
                    if (selected != undefined && selected.iid) {
                        let selectIndex = $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('getRowIndex', selected);
                        $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('editRow', selectIndex);
                    }
                }
            },
            {
                iconCls: 'icon-save', text: '保存', handler: function () {
                    $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('saveRow');
                }
            },
            {
                iconCls: 'icon-application_delete', text: '取消更改', handler: function () {
                    $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('cancelRow');
                }
            },
            {
                iconCls: 'icon-cancel', text: '删除', handler: function () {
                    let selected = $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('getSelected');
                    if (selected != undefined && selected.iid) {
                        $(`#${TABLE_ID_USER_CONTACT}`).edatagrid('destroyRow');
                    }
                }
            },
        ]
    })
}

// 返回上面表格选中的用户的ID
function getSelectedUserId(){
    let selected = $(`#${TABLE_ID_USER}`).edatagrid('getSelected');
    if (selected != undefined)
        return selected.id;
    else
        return 0;
}